/***********************************************************************************************************************************
 * Name:	DB_Update-Statistics-AllDBs.sql
 * Author:	Frank Figearo (frank@sqlnerd.me)
 * Summary:	Iterates through every database and updates statistics.
 */
SET ARITHABORT, IMPLICIT_TRANSACTIONS, XACT_ABORT OFF;
SET ARITHIGNORE ON;
SET DEADLOCK_PRIORITY HIGH;
IF 0 < @@TRANCOUNT ROLLBACK;
USE master
GO
DECLARE @tsql_command NVARCHAR(MAX);
DECLARE list CURSOR LOCAL FAST_FORWARD FOR
	SELECT tsql_command = REPLACE(N'USE [?]; EXECUTE sp_updatestats', '?', [name])
	  FROM sys.databases WHERE [state] = 0 AND database_id <> 2 ORDER BY database_id DESC;
OPEN list;
WHILE (0=0) BEGIN;
  FETCH NEXT FROM list INTO @tsql_command;
  IF @@FETCH_STATUS = 0 EXECUTE (@tsql_command) ELSE BREAK;
END;
CLOSE list;
DEALLOCATE list;
GO